package com.xm.xm.undercover.service

import android.app.Service
import android.content.Intent
import android.os.Binder
import android.os.Handler
import android.os.IBinder
import android.util.Log
import com.xm.xm.undercover.utils.ConstValue
import com.xm.xm.undercover.utils.JWebSocketClient
import com.xm.xm.undercover.utils.UserInfo
import org.java_websocket.handshake.ServerHandshake
import org.json.JSONObject
import java.net.URI
import androidx.core.os.HandlerCompat.postDelayed
import androidx.core.content.ContextCompat.getSystemService
import android.icu.lang.UCharacter.GraphemeClusterBreak.T
import androidx.core.content.ContextCompat.getSystemService
import android.icu.lang.UCharacter.GraphemeClusterBreak.T
import android.R.attr.name







class JWebSocketClientService : Service() {
    private val uri: URI? = null
    var client: JWebSocketClient? = null
    private val mBinder = JWebSocketClientBinder()

    //用于Activity和service通讯
    inner class JWebSocketClientBinder : Binder() {
        fun getService():JWebSocketClientService{
            return this@JWebSocketClientService
        }
    }

    override fun onBind(intent: Intent): IBinder {
        return mBinder
    }

    override fun onCreate() {
        super.onCreate()
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        // 初始化websocket
        Log.d("testActivity","start websocket")
        initWebSocket()
        return START_STICKY
    }

    private fun initWebSocket() {
        val path = "${ConstValue.url}${UserInfo.curUserId}/${UserInfo.curRoom}"
        Log.d("testActivity",path)
        val uri = URI.create(path)

        client = object : JWebSocketClient(uri) {
            override fun onMessage(message: String) {
                Log.e("JWebSocketClientService", "收到的消息：$message")

                val intent = Intent()
                intent.action = "com.xm.under.SOCKET"
                intent.putExtra("message", message)
                sendBroadcast(intent)
            }

            override fun onOpen(handshakedata: ServerHandshake) {
                super.onOpen(handshakedata)
                Log.e("JWebSocketClientService", "websocket连接成功")
            }
        }
        connectWS()
    }

    private fun connectWS() {
        Thread{
            client?.connectBlocking()
            // 发送个人信息，连接服务器
//        val message = GetMessage("7",null,null,"link")
            val message = JSONObject()
            message.put("id","7")
            message.put("mes","link")
            client?.send(message.toString())
        }.start()
    }

    override fun onDestroy() {
        super.onDestroy()
    }

    fun sendMsg(mes:String){
        Log.d("testActivity","发送："+mes)
        client?.send(mes)
    }

    fun closeConnect(){
        client?.close()
    }

    private val HEART_BEAT_RATE = (10 * 1000).toLong()
    val mHandler = Handler()
    private val heartBeatRunnable = object : Runnable {
        override fun run() {
            Log.e("JWebSocketClientService", "心跳包检测websocket连接状态")
            if (client!!.isClosed) {
              reConnect()
            } else {
                //如果client已为空，重新初始化连接
                client = null
                initWebSocket()
            }
            //每隔一定的时间，对长连接进行一次心跳检测
            mHandler.postDelayed(this, HEART_BEAT_RATE)
        }
    }

    fun reConnect(){
        mHandler.removeCallbacks(heartBeatRunnable)
        Thread{
            client?.reconnectBlocking()
        }.start()
    }
}